using System.Collections.Generic;
using Voodoo.Sauce.Internal.VoodooTune;
using Voodoo.Tune.Core;

namespace Voodoo.Sauce.Debugger
{
	public class VoodooTuneSegmentsDebugScreen : Screen
	{
		private Dictionary<Segment, DebugCheckboxButton> _checkboxButtons = new Dictionary<Segment, DebugCheckboxButton>();

		public override void OnScreenShow()
		{
			if (DebugVTManager.DraftDebugConfiguration == null)
			{
				DebugVTManager.NewDebugDraftConfiguration();
			}
			foreach (KeyValuePair<Segment, DebugCheckboxButton> kvp in _checkboxButtons)
			{
				kvp.Value.SetValue(DebugVTManager.DraftDebugConfiguration.SelectedSegments.Exists((Segment x) => x.Id == kvp.Key.Id));
			}
		}

		private void Start()
		{
			CreateSegmentsSection();
		}

		private void CreateSegmentsSection()
		{
			IEnumerable<Segment> debugSegments = DebugVTManager.GetDebugSegments();
			DebugVTConfiguration debugVTConfiguration = (DebugVTManager.IsDraftDebugConfiguration ? DebugVTManager.DraftDebugConfiguration : DebugVTManager.CurrentDebugConfiguration);
			Button("None", OnNoneSegmentButtonClicked);
			foreach (Segment segment in debugSegments)
			{
				Segment tempSegment = segment;
				DebugCheckboxButton debugCheckboxButton = CheckboxButton(segment.Name, delegate(bool value)
				{
					SelectSegment(value, tempSegment);
				});
				debugCheckboxButton.SetValue(debugVTConfiguration.SelectedSegments.Exists((Segment x) => x.Id == segment.Id));
				_checkboxButtons.Add(segment, debugCheckboxButton);
			}
		}

		private void OnNoneSegmentButtonClicked()
		{
			foreach (DebugCheckboxButton item in GetAll<DebugCheckboxButton>())
			{
				item.SetValue(value: false);
			}
			CheckConfiguration();
		}

		private void SelectSegment(bool value, Segment segment)
		{
			if (value)
			{
				DebugVTManager.AddDebugSegment(segment);
			}
			else if (DebugVTManager.RemoveDebugSegment(segment))
			{
				CheckConfiguration();
			}
		}

		private void CheckConfiguration(bool force = false)
		{
			DebugVTConfiguration draftDebugConfiguration = DebugVTManager.DraftDebugConfiguration;
			if (force || (draftDebugConfiguration != null && draftDebugConfiguration.HasNoneSelected))
			{
				DebugVTManager.ResetDebugDraftConfiguration();
				ResetRadioGroups(callCallback: false);
			}
		}
	}
}
